<?php

namespace app\marketing\controller;

use app\common\controller\Adminbase;
use app\model\DistributionSetting;
use app\model\Goods;
use app\model\GoodsCategory;
use app\model\GoodsFree;
use app\model\GoodsFree as GoodsFreeModel;
use app\model\GoodsType;

class Free extends Adminbase
{
    public function index()
    {
        $model = 'GoodsFree';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = GoodsFreeModel::where($map)
                ->alias('f')
                ->leftJoin('goods g', 'g.id = f.goods_id')
                ->field('f.*, g.title, g.image, g.sale_price, g.commission')
                ->withAttr('image', function ($value) {
                    return $value ? get_file_path($value, 1) : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->page($page, $pageSize)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select();
            $total  = GoodsFreeModel::where($map)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setLayerBtn([
                ['title' => '自动选择商品', 'url' => url('auto'), 'class' => 'layui-btn-normal'],
                ['title' => '手动选择商品', 'url' => url('select'), 'class' => '', 'area' => '["95vw", "100vh"]'],
                ['title' => '活动设置', 'url' => url('setting'), 'class' => ''],
            ])
            ->setConfirmBtn([
                ['title' => '一键删除', 'url' => url('delete_all'), 'class' => 'layui-btn-danger', 'msg' => '是否删除全部商品？']
            ])
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDataUrl()
            ->setLimit()
            ->setModel($model)
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('sort', '排序', null, null, false, '', false, '', true)
            ->addTableColumn('goods_id', '商品ID')
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('sale_price', '销售价格')
            ->addTableColumn('commission', '佣金')
            ->addTableColumn('sales', '活动销量')
            ->addTableOperation()
            ->returnForm();

        $this->assign('text', '新用户首购免单购买，金额由推客平台自己承担');
        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function auto()
    {
        $model = 'GoodsFree';

        $id = $this->request->param('id/d');
        if (isset($id) && $id > 0) {
            $info = GoodsFreeModel::get($id);
            $this->assign('id', $id);
            $this->assign('action', 2);
        } else {
            $info = [
                'min'    => 0,
                'max'    => 0,
                'source' => [2],
            ];
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $min  = intval($data['min']) * 100;
            $max  = intval($data['max']) * 100;
            if (empty($data['source'])) {
                return json(['code' => -1, 'msg' => '请选择商品来源范围']);
            }
            $goods_ids = Goods::where('status', 1)
                ->whereBetween('sale_price', [$min, $max])
                ->whereIn('source', $data['source'])
                ->column('id');
            if ($goods_ids) {
                $save = $this->createSaveData($goods_ids);
                if ($save) {
                    (new GoodsFree())->saveAll($save);
                }
            }

            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['close' => 1]]);
        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setUrl('auto')
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('min', 'gtnumber', '商品最低价', '', [], 1)
            ->addFormItem('max', 'gtnumber', '商品最高价', '', [], 1)
            ->addFormItem('source', 'checkbox', '商品来源范围', '', [2 => '公开商品', 1 => '定向商品'])
            ->setFormData($info)
            ->returnForm();
        $this->assign('no_return', 1);
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function select()
    {
        $model = 'Goods';

        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $list   = Goods::where($map)
                ->withAttr('source', function ($value, $data) {
                    $text = [1 => "<span class='layui-badge layui-bg-blue'>定向</span>", 2 => "<span class='layui-badge layui-bg-orange'>公开</span>"];
                    return $value ? $text[$value] : '';
                })
                ->withAttr('sale_price', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('share_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
                ->withAttr('subsidy_commission', function ($value) {
                    return $value > 0 ? number_format($value / 100, 2) : 0;
                })
               ->withAttr('plan_type', function ($value) {
                    $text = [1 => '定向计划', 2 => '公开计划', 3 => '机构定向计划', 4 => '机构普通计划'];
                    return $text[$value] ?? '';
                })
                ->field('*')
                ->page($page, $pageSize)
                ->order('sort asc, id desc')
                ->where('status', 1)
                ->with(['category', 'type'])
                ->select();
            $total  = Goods::where($map)->where('status', 1)->count();
            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        $category_list = GoodsCategory::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $category      = [];
        foreach ($category_list as $value) {
            if (!key_exists($value['id'], $category))
                $category[$value['id']] = $value['name'];
        }

        $type_list = GoodsType::field('id, name')
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
        $type      = [];
        foreach ($type_list as $value) {
            if (!key_exists($value['id'], $type))
                $type[$value['id']] = $value['name'];
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        $builder
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setSelectDataConfirmBtn([
                ['title' => '导入', 'url' => url('import'), 'class' => 'layui-btn-normal', 'msg' => '是否导入选中商品？'],
            ])
            ->setDataUrl('select')
            ->setFormUrl('form')
            ->addSearchItem('title', 'text', '商品标题')
            ->addSearchItem('product_id', 'text', '商品ID')
            ->addSearchItem('shop_appid', 'text', '小店ID')
            ->addSearchItem('category_id', 'select', '商品分类', $category)
            ->addSearchItem('type', 'select', '商品专区', $type)
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox('left')
            ->setSwitchTpl('switchTpl', 'status')
            ->setSwitchTpl('amplifyTpl', 'image')
            ->addTableColumn('id', 'ID', null, null, true)
            ->addTableColumn('source', '来源', 120)
            ->addTableColumn('plan_type', '计划类型销售价格', 130)
            ->addTableColumn('product_id', '商品ID', 180)
            ->addTableColumn('title', '标题', 550)
            ->addTableColumn('sale_price', '销售价格', 150)
            ->addTableColumn('commission', '佣金', 150)
            ->addTableColumn('image', '图片', null, '#amplifyTpl')
            ->addTableColumn('category_name', '商品分类', 120)
            ->addTableColumn('type_name', '商品专区', 120)
            ->addTableColumn('stock_num', '库存', 120)
            ->addTableColumn('subsidy_commission', '补贴佣金', 150)
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function import()
    {
        $ids = $this->request->param('ids');
        if ($ids) {
            $save = $this->createSaveData($ids);
            if ($save) {
                (new GoodsFree())->saveAll($save);
            }
        }
        return json(['code' => 0, 'msg' => '导入成功', 'data' => ['close' => 1]]);
    }

    public function createSaveData($goods_ids)
    {
        $db_ids = GoodsFreeModel::where('goods_id', 'gt', 0)->column('goods_id');
        $save   = [];
        foreach ($goods_ids as $goods_id) {
            if (!in_array($goods_id, $db_ids)) {
                $save[] = [
                    'goods_id' => $goods_id,
                ];
            }
        }
        return $save;
    }

    public function delete_all()
    {
        GoodsFreeModel::where('id', '>', 0)->delete();
        return json(['code' => 0, 'msg' => '删除成功']);
    }

    public function setting()
    {
        $uuid = 'free';
        $info = DistributionSetting::where('uuid', $uuid)->find();
        if (empty($info)) {
            $info = [
                'uuid'  => $uuid,
                'name'  => '新人0元购活动设置',
                'type'  => 0,
                'value' => json_encode(['is_pop' => 0, 'is_expire' => 0]),
            ];
            DistributionSetting::create($info);
        } else {
            $info['value'] = json_decode($info['value'], true);
        }

        $model = 'ShopCategory';

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($data['is_expire'] == 1) {
                if (empty($data['start_date']) || empty($data['end_date'])) {
                    return json(['code' => -1, 'msg' => '请选择活动开始时间和结束时间']);
                }
            }

            $save = [
                'is_expire'   => $data['is_expire'],
                'start_date'  => $data['start_date'],
                'end_date'    => $data['end_date'],
                'is_pop'      => $data['is_pop'],
                'pop'         => $data['pop'],
                'share_title' => $data['share_title'],
                'share'       => $data['share'],
            ];
            DistributionSetting::where('uuid', $uuid)->update([
                'value' => json_encode($save, JSON_UNESCAPED_UNICODE),
            ]);
            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['close' => 1]]);
        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setUrl('setting')
            ->setModel($model)
            ->setSuccessUrl()
            ->addFormItem('is_expire', 'radio', '是否长期有效', '', [0 => '长期有效', 1 => '时间段开启'])
            ->addFormItem('start_date', 'date', '活动开始时间')
            ->addFormItem('end_date', 'date', '活动结束时间')
            ->addFormItem('is_pop', 'radio', '活动弹窗', '', [0 => '关闭', 1 => '开启'])
            ->addFormItem('pop', 'image', '弹窗图片')
            ->addFormItem('share_title', 'text', '转发标题')
            ->addFormItem('share', 'image', '转发图片')
            ->setFormData($info['value'])
            ->returnForm();
        $this->assign('no_return', 1);
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

}
